package com.jdbc.transaction;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository("bookShopSao")
public class BookShopDaoImpl implements BookShopDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public int findBookPriceByIsbn(String isbn) {
		String sql = "select price from book where isbn=?";
		return jdbcTemplate.queryForObject(sql, Integer.class, isbn);
	}

	@Override
	public void updateBookStock(String isbn) {
		// 检查书的库存，不足则抛出异常
		String sql2 = "select stock from book_stock where isbn=?";
		int stock = jdbcTemplate.queryForObject(sql2, Integer.class, isbn);
		if (stock == 0) {
			throw new BookStockException("书的数量不够了");
		}

		String sql = "update book_stock set stock=stock-1 where isbn=?";
		jdbcTemplate.update(sql, isbn);
	}

	@Override
	public void updateUserAccount(String userName, int price) {
		// 验证用户余额，不足则抛出异常
		String sql2 = "select balance from account where userName=?";
		int balance = jdbcTemplate.queryForObject(sql2, Integer.class, userName);
		if (balance < price) {
			throw new UserAccountException("余额不够了");
		}

		String sql = "update account set balance = balance - ? where username=?";
		jdbcTemplate.update(sql, price, userName);

	}

}
